<template>
	<uni-popup ref="fileNameInputRef" type="dialog" class="fileNameInputPopup">
		<uni-popup-dialog
			mode="input"
			:title="props.title"
			:confirmText="props.confirmText"
			:cancelText="props.cancelText"
			:maxlength="props.maxlength"
			:showClose="props.showClose"
			:placeholder="props.placeholder"
			:borderRadius="props.borderRadius"
			v-model="name"
			:before-close="true"
			@close="cancel"
			@confirm="dialogInputConfirm">
		</uni-popup-dialog>
		<uni-popup ref="msgRef" type="message">
			<uni-popup-message :type="msgType" :message="msg" :duration="2000"></uni-popup-message>
		</uni-popup>
	</uni-popup>
</template>

<script lang="ts" setup>
import { validateFilename } from "@/utils/fileUtil";
import { ref, defineProps, withDefaults, defineEmits, watch, defineExpose } from "vue";
import type { PopupMessageType } from "../../type/type";

const name = ref("");
const msg = ref("");
const msgType = ref<PopupMessageType>("success");
const msgRef = ref(null);
const fileNameInputRef = ref(null);

interface Props {
	fileName: string
	title: string
	confirmText: string
	cancelText: string
	maxlength?: number
	showClose: boolean
	placeholder: string
	borderRadius?: string
	beforeClose: boolean
}

const props = withDefaults(defineProps<Props>(), {
	fileName: "",
	title: "输入文件名",
	confirmText: "确定",
	cancelText: "使用默认文件名",
	showClose: true,
	placeholder: "请输入文件名"
})

watch(() => props.fileName, (newVal) => {
	name.value = newVal;
})

const emit = defineEmits<{
	(e: "confirm", type: string): void,
	(e: "cancel"): void,
}>()

// 点击取消
function cancel() {
	emit("cancel");
}

// 点击确认
function dialogInputConfirm(val: string) {
	const res = validateFilename(val);
	if (!res.isValid) {
		msg.value = res.message;
		msgType.value = "error";
		msgRef.value.open();
		return;
	}
	msgType.value = "success";
	msg.value = "添加文件名成功";
	msgRef.value.open();
	emit("confirm", name.value);
}

defineExpose({
	open: () => {
		fileNameInputRef.value.open();
	},
	close: () => {
		fileNameInputRef.value.close();
	}
})
</script>

<style lang="scss" scoped>

</style>